import {
  Controller,
  Post,
  Get,
  Body,
  UseGuards,
  Request,
  Query,
  Param,
  ParseIntPipe,
  Res,
  Req,
  Render,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiQuery,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { ShareService } from './share.service';
import {
  CreateShareLinkDto,
  ShareLinkResponseDto,
  ClickShareLinkDto,
  ClickShareLinkResponseDto,
  ShareStatsResponseDto,
  ShareHistoryResponseDto,
} from './dto/share.dto';
import express from 'express';

@ApiTags('分享功能')
@Controller('share')
export class ShareController {
  constructor(private readonly shareService: ShareService) {}

  @Post('create')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '创建分享链接' })
  @ApiResponse({
    status: 200,
    description: '创建成功',
    type: ShareLinkResponseDto,
  })
  @ApiResponse({ status: 400, description: '参数错误' })
  @ApiResponse({ status: 401, description: '未授权' })
  async createShareLink(@Request() req, @Body() createDto: CreateShareLinkDto) {
    const userId = req.user.id;
    const result = await this.shareService.createShareLink(userId, createDto);

    return {
      code: 200,
      message: '创建分享链接成功',
      data: result,
      timestamp: Date.now(),
    };
  }

  @Get('redirect')
  @ApiOperation({ summary: '显示重定向页面' })
  @ApiQuery({ name: 'token', description: '分享token', required: true })
  @ApiQuery({ name: 'url', description: '目标URL', required: true })
  @ApiQuery({ name: 'type', description: '分享类型', required: false })
  @ApiQuery({ name: 'id', description: '目标ID', required: false })
  async showRedirectPage(
    @Query('token') token: string,
    @Query('url') targetUrl: string,
    @Query('type') shareType: string = 'APP',
    @Query('id') targetId: string = '',
    @Res() res: express.Response,
  ) {
    if (!token || !targetUrl) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        timestamp: Date.now(),
      });
    }
    console.log(token, targetUrl, shareType, targetId);

    try {
      // 验证分享链接是否存在
      const shareLink = await this.shareService.getShareLinkByToken(token);
      if (!shareLink) {
        return res.status(404).json({
          code: 404,
          message: '分享链接不存在',
          timestamp: Date.now(),
        });
      }

      // 获取内容信息（短剧或章节信息）
      let contentInfo = null;
      if (shareType === 'SHORT' || shareType === 'CHAPTER') {
        contentInfo = await this.shareService.getContentInfo(shareType, parseInt(targetId));
      }

      // 读取重定向页面模板
      const fs = require('fs');
      const path = require('path');
      const templatePath = path.join(
        __dirname,
        '../../share/templates',
        'redirect.html',
      );
      let template = fs.readFileSync(templatePath, 'utf8');

      // 替换模板变量
      template = template.replace(
        /\{\{targetUrl\}\}/g,
        targetUrl + '/share/' + shareType + '/' + targetId + '?token=' + token,
      );
      template = template.replace(/\{\{shareType\}\}/g, shareType);
      template = template.replace(/\{\{targetId\}\}/g, targetId);

      // 添加内容信息到模板
      if (contentInfo) {
        if (shareType === 'SHORT') {
          // 短剧分享
          const shortInfo = contentInfo as {
            title?: string;
            coverUrl?: string;
            summary?: string;
            instructor?: string;
          };
          template = template.replace(/\{\{contentTitle\}\}/g, shortInfo.title || '');
          template = template.replace(/\{\{contentCoverUrl\}\}/g, shortInfo.coverUrl || '');
          template = template.replace(/\{\{contentSummary\}\}/g, shortInfo.summary || '');
          template = template.replace(/\{\{contentInstructor\}\}/g, shortInfo.instructor || '');
        } else if (shareType === 'CHAPTER') {
          // 章节分享
          const chapterInfo = contentInfo as {
            title?: string;
            shorts?: {
              title?: string;
              coverUrl?: string;
              summary?: string;
              instructor?: string;
            };
          };
          template = template.replace(/\{\{contentTitle\}\}/g, chapterInfo.shorts?.title || '');
          template = template.replace(/\{\{contentCoverUrl\}\}/g, chapterInfo.shorts?.coverUrl || '');
          template = template.replace(/\{\{contentSummary\}\}/g, chapterInfo.shorts?.summary || '');
          template = template.replace(/\{\{contentInstructor\}\}/g, chapterInfo.shorts?.instructor || '');
          template = template.replace(/\{\{chapterTitle\}\}/g, chapterInfo.title || '');
        }
      } else {
        // 如果没有内容信息，使用默认值
        template = template.replace(/\{\{contentTitle\}\}/g, '');
        template = template.replace(/\{\{contentCoverUrl\}\}/g, '');
        template = template.replace(/\{\{contentSummary\}\}/g, '');
        template = template.replace(/\{\{contentInstructor\}\}/g, '');
        template = template.replace(/\{\{chapterTitle\}\}/g, '');
      }

      // 返回HTML页面
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      return res.send(template);
    } catch (error) {
      console.log(error);
      return res.status(500).json({
        code: 500,
        message: '服务器错误',
        timestamp: Date.now(),
      });
    }
  }

  @Get()
  @ApiOperation({ summary: '访问分享链接' })
  @ApiQuery({ name: 'token', description: '分享token', required: true })
  @ApiResponse({
    status: 200,
    description: '访问成功',
    type: ClickShareLinkResponseDto,
  })
  @ApiResponse({ status: 400, description: '链接无效' })
  @ApiResponse({ status: 404, description: '链接不存在' })
  async visitShareLink(
    @Query('token') token: string,
    @Req() req: any,
    @Res() res: express.Response,
  ) {
    if (!token) {
      return res.status(400).json({
        code: 400,
        message: '缺少分享token',
        timestamp: Date.now(),
      });
    }

    try {
      // 获取用户信息（如果已登录）
      const userId = req.user?.id;

      // 获取IP地址和用户代理
      const ipAddress =
        req.ip ||
        req.connection.remoteAddress ||
        req.headers['x-forwarded-for'];
      const userAgent = req.headers['user-agent'];

      const clickDto: ClickShareLinkDto = {
        shareToken: token,
        ipAddress,
        userAgent,
      };

      const result = await this.shareService.clickShareLink(clickDto, userId);

      // 根据分享类型重定向到不同的页面
      const shareLink = await this.shareService.getShareLinkByToken(token);

      if (shareLink) {
        let redirectUrl = process.env.APP_DOWNLOAD_URL;

        if (shareLink.shareType === 'SHORTS' && shareLink.targetId) {
          redirectUrl = `${process.env.FRONTEND_URL}/shorts/${shareLink.targetId}`;
        } else if (shareLink.shareType === 'CHAPTER' && shareLink.targetId) {
          redirectUrl = `${process.env.FRONTEND_URL}/chapter/${shareLink.targetId}`;
        }

        // 重定向到重定向页面，而不是直接跳转
        const redirectPageUrl = `/api/share/redirect?token=${token}&url=${encodeURIComponent(redirectUrl!)}&type=${shareLink.shareType}&id=${shareLink.targetId || ''}`;
        return res.redirect(redirectPageUrl);
      } else {
        return res.status(404).json({
          code: 404,
          message: '分享链接不存在',
          timestamp: Date.now(),
        });
      }
    } catch (error) {
      return res.status(400).json({
        code: 400,
        message: error.message,
        timestamp: Date.now(),
      });
    }
  }

  @Post('click')
  @ApiOperation({ summary: '点击分享链接（API方式）' })
  @ApiResponse({
    status: 200,
    description: '点击成功',
    type: ClickShareLinkResponseDto,
  })
  @ApiResponse({ status: 400, description: '链接无效' })
  @ApiResponse({ status: 404, description: '链接不存在' })
  async clickShareLink(@Body() clickDto: ClickShareLinkDto, @Request() req) {
    // 获取用户信息（如果已登录）
    const userId = req.user?.id;

    // 如果没有提供IP地址，从请求中获取
    if (!clickDto.ipAddress) {
      clickDto.ipAddress =
        req.ip ||
        req.connection.remoteAddress ||
        req.headers['x-forwarded-for'];
    }

    // 如果没有提供用户代理，从请求中获取
    if (!clickDto.userAgent) {
      clickDto.userAgent = req.headers['user-agent'];
    }
    console.log(clickDto);
    clickDto.shareToken = clickDto.shareToken;

    const result = await this.shareService.clickShareLink(clickDto, userId);

    return {
      code: 200,
      message: '操作成功',
      data: result,
      timestamp: Date.now(),
    };
  }

  @Get('stats')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取分享统计' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: ShareStatsResponseDto,
  })
  @ApiResponse({ status: 401, description: '未授权' })
  async getShareStats(@Request() req) {
    const userId = req.user.id;
    const result = await this.shareService.getUserShareStats(userId);

    return {
      code: 200,
      message: '获取分享统计成功',
      data: result,
      timestamp: Date.now(),
    };
  }

  @Get('history')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取分享历史' })
  @ApiQuery({
    name: 'page',
    description: '页码',
    required: false,
    type: Number,
  })
  @ApiQuery({
    name: 'pageSize',
    description: '每页数量',
    required: false,
    type: Number,
  })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: ShareHistoryResponseDto,
  })
  @ApiResponse({ status: 401, description: '未授权' })
  async getShareHistory(
    @Request() req,
    @Query('page') page: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    const userId = req.user.id;
    const result = await this.shareService.getUserShareHistory(
      userId,
      Number(page),
      Number(pageSize),
    );

    return {
      code: 200,
      message: '获取分享历史成功',
      data: result,
      timestamp: Date.now(),
    };
  }

  @Post('deactivate/:id')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '禁用分享链接' })
  @ApiResponse({ status: 200, description: '禁用成功' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 404, description: '分享链接不存在' })
  async deactivateShareLink(
    @Request() req,
    @Param('id', ParseIntPipe) shareLinkId: number,
  ) {
    const userId = req.user.id;
    await this.shareService.deactivateShareLink(userId, shareLinkId);

    return {
      code: 200,
      message: '禁用分享链接成功',
      timestamp: Date.now(),
    };
  }
}
